package com.example.hans.internetandroid;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class TestActivity extends AppCompatActivity implements View.OnClickListener, HttpUtil.OnNeedSendFlag{

    private static String TAG = "TestActivity";

    private Button mButton;
    private EditText mEditText;
    private TextView mTextView;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    mTextView.setText((String)msg.obj);
                    break;
                }
                case 2: {
                    mTextView.setText((String)msg.obj);
                    Log.d(TAG,"网络请求失败");
                    break;
                }
                default:
            }
        }
    };

    private HttpUtil mHttpUtil;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testactivity_layout);

        mButton = findViewById(R.id.btn_request);
        mEditText = findViewById(R.id.et_request_url);
        mTextView = findViewById(R.id.tv_showMessage);

        mHttpUtil = new HttpUtil();
        mHttpUtil.setOnNeedSendFlag(this);

        mButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_request: {
                String url = mEditText.getText().toString();
                if (url != null && !url.equals("")) {
                    mHttpUtil.sendRequest(url);
                }
                break;
            }
            default:
        }
    }

    @Override
    public void onNeedSeedFinishMsg(String finishMessage) {
        Message msg = new Message();
        msg.what = 1;
        msg.obj = finishMessage;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onNeedSeedErrorMsg(String errorMessage) {
        Message msg = new Message();
        msg.what = 2;
        msg.obj = errorMessage;
        mHandler.sendMessage(msg);
    }
}
